/**
 *
 * Copyright 2016-present scrm
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
import { SCRM_HOST } from '../constants/Urls';
import store from 'react-native-simple-store';
const _ = require('lodash');


export const getDefaultLink = (base, query, route, mode) => {
  base = base ? base : SCRM_HOST;
  mode = mode ? mode : 'hash'
  try {
    return new Promise((resolve, reject) => {
      store.get('site_id').then(site_id => {
        query = Object.assign({ runtime: 'react', 'site_id': site_id, 'timestamp': 1237912378 },  (query || {}));
        const link = getLink(base, query, (route || {}), mode);
        resolve(link);
      }).catch((error) => {
        const link = getLink(base, {}, (route || {}), mode);
        resolve(link);
      })
    })
  } catch (error) {
    console.log(error);
  }
}


export const getLink = (base, query, route, mode) => {
  let link;
  if (mode === 'hash') {
    link = createHref(
      base + '?' + buildQuery(query), 
      route.path + '?' + buildQuery(route.params),
      mode)
  } else {
    link = createHref(
      base,
      route.path,
      Object.assign(query, route.params || {})
    );
  }
  return link;
}


export const getLinkSimple = (route) => {
  return getDefaultLink(null, null, route);
}

export const buildQuery = (args) => {
  let paramsArray = []
  _.forEach(args, (value, property) => {
    paramsArray.push(property + '=' + encodeURIComponent(value))
  });
  // console.log('params.article.url', paramsArray.join('&'));
  return paramsArray.join('&');
}

export const cleanPath = (path) => {
  return path.replace(/\/\//g, '/')
}

export const createHref = (base, fullPath, mode) => {
  var path = mode === 'hash' ? '#/' + fullPath : fullPath;
  return base ? (base + (mode === 'hash' ? '' : '/') + path) : path
}